package com.hyy.asm.protocol;

import com.hyy.asm.message.LoginRequestMessage;
import com.hyy.asm.message.Message;
import com.hyy.asm.config.Config;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class TestSerializer {

    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LoggingHandler(LogLevel.DEBUG),
                new MessageCodecSharable());
        LoginRequestMessage message = new LoginRequestMessage("zhangsan","123");
//        channel.writeOutbound(message);
        ByteBuf buf = messageToByteBuf(message);
        channel.writeInbound(buf);
    }



    static ByteBuf messageToByteBuf(Message msg) throws Exception {
        ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
        //1、4 字节的魔数
        out.writeBytes(new byte[]{1,2,3,4});
        //2、1 字节的版本
        out.writeByte(1);
        //3、1 字节的序列化方式 0 jdk 1 json
        out.writeByte(Config.getSerializerAlgorithm().ordinal());
        //4、1 字节的指令类型
        out.writeByte(msg.getMessageType());
        //5、4 字节的指令序号
        out.writeInt(msg.getSequenceId());
        out.writeByte(0xff);
        //6、获取字节数组
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        ObjectOutputStream oos = new ObjectOutputStream(baos);
//        oos.writeObject(msg);
//        byte[] bytes = baos.toByteArray();
        byte[] bytes = Config.getSerializerAlgorithm().serialize(msg);
        //7、4 字节的长度
        out.writeInt(bytes.length);
        //8、内容
        out.writeBytes(bytes);
        return out;
    }
}
